package reqHandler;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import models.HibernateTags;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

public class ReqXMLParser {
	
	private Element root;
	private HashMap<Integer, String> stopliste;
	private String stoplistPath;
	private File file;

	public ReqXMLParser (String docPath, String slPath, String resultFilePath) {
		this.stopliste = new HashMap<Integer, String>(); // preparing the stopliste
		this.stoplistPath = slPath;
		this.file= new File(resultFilePath); // preparing the result file
		try {
			if (!file.exists()){
				file.createNewFile();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		SAXBuilder builder = new SAXBuilder();
        try {
        	Document doc = builder.build(new File(docPath));
        	this.root = doc.getRootElement();
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}       
        
	}
	
	public void parseDoc () {
		List<Element> children= root.getChildren();
		Iterator<Element> i = children.iterator();
		setStopListe(stoplistPath);
		ReqHandler rh = new ReqHandler(stopliste);
		try {
			int j = 1;
			while (i.hasNext()){ // while the element has cildren (queries)
				FileWriter fw = new FileWriter(file.getAbsoluteFile()+"/result"+j+".txt"); // preparing the result file writing
				BufferedWriter bw = new BufferedWriter(fw);
				Element e = i.next();
				String query = e.getChildText("text");
				System.out.println(e.getAttributeValue("id") + " : " + query);
				printResults(rh.execQueryWithSparql(query),bw); // launching with SPARQL
				//printResults(rh.execQuery(query),bw); // Launching without SPARQL
				bw.close();
				j++;
			}
		} catch (IOException e){
			e.printStackTrace();
		}
	}
	
	private void printResults (ArrayList<HibernateTags> liste,BufferedWriter bw) throws IOException{
		for (int i=0; i<liste.size(); i++) { // writing in the result file
			String msg = "  " +liste.get(i).getDocID().getNom()+liste.get(i).getxPath()+"\n";
			System.out.print(msg);
			bw.write(msg);
		}
			
	}
	
	public void setStopListe(String stoplistPath){ // stopListe setting
		BufferedReader br=null;
		String line;
		try {
			br = new BufferedReader(new FileReader(stoplistPath));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		try {
			int i=0;
			while ((line = br.readLine()) != null) {
			   stopliste.put(i, line);
			   i++;
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	
	public static void main (String[] args) {
		ReqXMLParser req = new ReqXMLParser(args[0],args[1], args[2]);
		req.parseDoc();
	}

}
